<?php
namespace LRP;

use LRP\Contract\RegisterInterface;

/**
 * Class Register
 *
 * PHP Version > 7.0
 *
 * @package LRP
 * @author  Jon
 * @link    https://gitee.com/joncc/long-running-processor
 */
class Register implements RegisterInterface
{
    const TUBE_NUM_DEFAULT = 1;

    private static $instance;
    private static $handles = [];
    private static $tube_num = [];

    /**
     * Register constructor.
     */
    private function __construct()
    {
    }

    /**
     * @return Register
     */
    public static function instance(): self
    {
        if (empty(self::$instance)) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * @param array $handles
     */
    public static function register(array $handles): void
    {
        if (!is_array($handles)) {
            return;
        }

        self::$handles = $handles;
        foreach ($handles as $tube => $handle) {
            self::setTubeLineNum($tube, self::TUBE_NUM_DEFAULT);
        }
    }

    /**
     * @param string $tube
     * @param int $num
     * @return bool
     */
    public static function setTubeLineNum(string $tube, int $num): bool
    {
        if (!self::has($tube)) {
            return false;
        }

        self::$tube_num[$tube] = $num;
        return true;
    }

    /**
     * @param string $tube
     * @return int
     */
    public static function getTubeLineNum(string $tube): int
    {
        return self::has($tube) ? self::$tube_num[$tube] : self::TUBE_NUM_DEFAULT;
    }

    /**
     * @param string $tube
     * @return string
     */
    public static function getHandle(string $tube): string
    {
        return self::has($tube) ? self::$handles[$tube] : false;
    }

    /**
     * @param string $tube
     * @return bool
     */
    public static function has(string $tube): bool
    {
        return key_exists($tube, self::$handles);
    }

    /**
     * @return array
     */
    public static function getTubes(): array
    {
        return array_keys(self::$handles);
    }
}